<template>
  <!-- 维修套餐维护 -->
  <div>
    <!--条件筛选-->
    <TopFilter :list="topFilterList" :cols="3" labelWidth="90" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!--操作 -->
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <!-- 列筛选-->
    <FilterTable
      ref="table"
      columnsRef="repair-package-index"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectData"

    >
      <!-- :isExportExcel2="true"
      :exportFileName="'维修套餐信息.xlsx'" -->
      <!--列操作-->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addFn('add')">新增套餐</el-button>
        <multiuse-button size="small" type="primary" :click="repairPackageDistributeClick.bind()">发布</multiuse-button>
        <el-button size="small" type="primary" icon="el-icon-upload" @click="exportClick">导出</el-button>
        <!-- <UploadFile style="margin: 0 10px;" :isOnlyButton="true" :limit="99" :actionUrl="`${server.DMSCLOUD_REPAIR}/repair/group/importRepairItemPackage`" @change="handleUploadChange"
          >Excel导入</UploadFile
        > -->
      </template>
    </FilterTable>

    <!--抽屉 -->
    <Drawer :visible.sync="estimate" :title="dialogTitle" :width="1100" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <repairPackageInfo :type="handleType" :info="formData" @close="closeEstimate" />
    </Drawer>
     <Drawer :visible.sync="showAddPackage" :title="showAddPackageTitle" width="70%" destroyOnClose>
      <addPackage :activityCode="activityCode" @close="closeAddPackage"></addPackage>
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import SERVER from '@/api/server';
import { mutations } from './store';
import { releaseActivity, ActivityForExport, exportActivity,getRepairTypes, getAllSeries, exportRepairItemPackage,
        changeStatus, getAllUser,queryActivityAll,updateActivity } from '@/api/repair/repairBusiness/repairPackage';
 import {getDealerUser,} from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import repairPackageInfo from '@/pages/repair/repairBusiness/repairPackage_oem/repairPackageInfo';
import { getAppId } from '@/assets/js/auth';
import addPackage from './addPackage.vue';
import { getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index';//事业部，办事处

// 延保订单查询
export default {
  name: 'repair-package-index',
  components: { repairPackageInfo ,addPackage},
  mixins: [dictionary],
  data() {
    return {
      server: SERVER,
      form: {
        fileList: []
      },
      showAddPackage: false,
      showAddPackageTitle: '新增套餐',
      conf : { add: '新增套餐', edit: '编辑套餐', show: '套餐明细' },
      fetchParams: { xhrAbort: false },
      dialogTitle: '',
      fetchApi: queryActivityAll,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      tableData: [],
      selectFlag: false,
      topFilterList: this.createTopFilterList(),
      estimate: false,
      environmentalDate: {},
      serviceAdvisorList: [],
      wxlxList: [],
      onChangeColumn: [],
      activityCode: '',
      selectedRows:[]
    };
  },
  created() {
    this.getRepairTypesFun();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getAllUser();
    this.getAllSeries(); // 不需要翻译code
    this.setFieldHidden(); // 设置字段禁用状态
     this.getBigArea();
  },
  methods: {

     closeAddPackage(n) {
      console.log(n, 'closeAddPackage==');
      this.showAddPackage = false;
      if (n === 'success') {
        this.fetchParams = { ...this.fetchParams, xhrAbort: false };
      }
    },
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode === 200) {
        let allUser = res.data.map(x => ({
          text: x.employeeName,
          value: x.userId + ''
        }));
        this.columns.find(x => x.dataIndex === 'releaseBy').dictItems = allUser;

      }
    },

    // 获取套餐代码
    async getCodeFun() {
      const res = await getActivityCode({ 'ownerCode': '-1' });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'warning');
        } else {
          // this.findFormItem('activityCode').initialValue = res.data;
          this.activityCode = res.data;
        }
      }
    },
    addFn(n, data) {
     mutations.setPackageType(n);
      if (n === 'add') {
        this.showAddPackageTitle = '新增套餐';
        this.showAddPackage = true;
        // this.getCodeFun();

        return;
      } else {
        if (n === 'look') {
          this.showAddPackageTitle = '套餐明细';
        } else {
          this.showAddPackageTitle = '编辑套餐';
        }

        this.activityCode = data.activityCode;
        this.isParticipate = data.isParticipate;
        this.showAddPackage = true;
      }

    },
    async getAllSeries() {
      let res = await getAllSeries();
      if (res.resultCode === 200) {
        let series = res.data.map(x => {
          return { value: x.seriesCode, text: x.seriesName };
        });
        this.topFilterList.find(x => x.fieldName === 'SERIES_CODE').itemList = series;
      }
    },

    // 导入成功事件
    handleUploadChange(e) {
      console.log('导入文件上传成功', e.length);
      if (e.length > 0) {
        this.$notify.success({ title: '提示信息', message: '导入成功!!!' });
        this.fetchParams = Object.assign({}, this.fetchParams);
        // this.loading = false;
      }
    },
    async exportClick() {
      let params = { ...this.fetchParams };
      console.log(params, '导出::');
      let res = await ActivityForExport(params);

      console.log(res.data, '导出数据::');
      try {
        exportExcelFile(res.data, '套餐查询');
      } catch (e) {
        console.log(e, '错误::');
      }
    },
    importClick() {},
    // async repairPackageDistributeClick() {
    //   let packageCodes = [];
    //   this.tableData.forEach(x => {
    //     packageCodes.push(x.PACKAGE_CODE);
    //   });
    //   let res = await repairPackageDistribute(packageCodes);
    //   if (res.resultCode === 200) {
    //     this.$notify.success({ title: '提示信息', message: '下发成功！！' });
    //   }
    // },

    async repairPackageDistributeClick() {
      if (this.selectedRows.length > 0) {
        let ids = '';
        let endDate = '';
        let releaseTag = 0;
        this.selectedRows.map((x) => {
          ids += x.activityCode + ',';
          endDate = x.endDate;
          releaseTag = x.releaseTag;
        });
        //获取当前时间
          var date = new Date();
          var year = date.getFullYear(); //月份从0~11，所以加一
          var dateArr = [date.getMonth() + 1,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds()];
          for(var i=0;i<dateArr.length;i++){
            if (dateArr[i] >= 1 && dateArr[i] <= 9) {
                dateArr[i] = "0" + dateArr[i];
            }
          }
        var strDate = year+'-'+dateArr[0]+'-'+dateArr[1]+' '+dateArr[2]+':'+dateArr[3]+':'+dateArr[4];
        if(releaseTag == 10141002){//待下发

            if(endDate>=strDate){//活动结束日期大于当前时间
            const res = await releaseActivity({ ids});
              this.$notify.success({ title: '提示信息', message: '发布成功' });
              this.fetchParams = { ...this.fetchParams };//更新

            }else{
               this.$notify.warning({ title: '提示信息', message: '活动截止日期小于当前日期，不能发布' });
                            // this.fetchParams = { ...this.fetchParams };//更新


            }
        }else if(releaseTag == 10141003){//10141003
             this.$notify.warning({ title: '提示信息', message: '该套餐已发布！' });
                          // this.fetchParams = { ...this.fetchParams };//更新


        }else if(releaseTag == 10141005){//
             this.$notify.warning({ title: '提示信息', message: '该套餐已作废！' });
                          // this.fetchParams = { ...this.fetchParams };//更新


        }else{
             this.$notify.warning({ title: '提示信息', message: '该套餐已关闭！' });
                          // this.fetchParams = { ...this.fetchParams };//更新


        }
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行发布！' });
      }
    },

    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes();
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
      this.topFilterList.find(x => x.fieldName === 'REPAIR_TYPE_CODE').itemList = this.repairList;
      this.columns.find(x => x.dataIndex === 'REPAIR_TYPE_CODE').dictItems = this.repairList;
      this.columns.find(x => x.dataIndex === 'REPAIR_TYPE_CODE').filterItems = this.repairList;
    },
        //获取大，小区
    async getBigArea() {
      const res = await getLevelTwoAndThreeArea(15061020,null);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'serviceBigArea').itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
      }

        const res1 = await getLevelTwoAndThreeArea(15061021,null);
      if (res1.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'serviceSmallArea').itemList = res1.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '套餐代码',
          fieldName: 'activityCode'
        },
        {
          type: 'INPUT',
          label: '套餐名称',
          fieldName: 'activityName'
        },
        {
          type: 'SELECT',
          label: '套餐类型',
          fieldName: 'activityType',
          itemList: this.createDictList('5601')
        },
        {
          type: 'SELECT',
          label: '发布状态',
          fieldName: 'releaseTag',
          itemList: this.createDictList(1014, [10141001,10141006])
        },
        {
          type: 'DATE',
          label: '开始日期',
          fieldName: 'startDate',
          dateType: 'date',
          valueFormat: 'yyyy-MM-dd'
        },

        {
          type: 'DATE',
          label: '结束日期',
          fieldName: 'endDate',
          dateType: 'date',
          valueFormat: 'yyyy-MM-dd'
        },

      ];
    },
    createTableColumns() {
       return [
         {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          width: 130,
          render: props => {
            return (
              //  <el-button size='mini' disabled={props.row.releaseTag + '' === '10041001' || props.row.dataSource + '' === '10451002'} type='text' onClick={() => this.pushFn(props.row)}>
              //     发布
              //   </el-button>
              <div>
                <el-button size='mini' type='text' disabled={props.row.releaseTag + '' === '10141003' || props.row.releaseTag + '' === '10141004'|| props.row.releaseTag + '' === '10141005'} onClick={() => this.addFn('edit', props.row)}>
                  编辑
                </el-button>

                <el-button size='mini'  type='text' onClick={() => this.addFn('look', props.row)}>
                  明细
                </el-button>
                <el-button size='mini' disabled={props.row.releaseTag + '' === '10141004'|| props.row.releaseTag + '' === '10141005'} type='text' onClick={() => this.invalid(props.row)}>
                  作废
                </el-button>
              </div>
            );
          }
        },

        {
          title: '套餐代码',
          dataIndex: 'activityCode',
          width: 130,
          // render: props => {
          //   return (
          //     <el-button size='mini' type='text' onClick={() => this.addFn('look', props.row)}>
          //       {props.row.activityCode}
          //     </el-button>
          //   );
          // }
        },
        {
          title: '套餐名称',
          dataIndex: 'activityName',
          width: 130
        },
        {
          title: '套餐类型',
          dataIndex: 'activityType',
          editable: false,
          editType: 'select',
          // width: 120,
          editItems: this.createDictList('5601')
        },
       {
          title: '发布状态',
          dataIndex: 'releaseTag',
           editType: 'select',
          // width: 120,
          editItems: this.createDictList('1014'),
          // render: props => {
          //   return <span>{props.row.releaseTag + '' === '10041001' ? '已发布' : '未发布'}</span>;
          // }
        },
        {
          title: '开始日期',
          dataIndex: 'startDate'
        },
        {
          title: '结束日期',
          dataIndex: 'endDate'
          // dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '套餐明细不可删除',
          dataIndex: 'isAllowDeleted',
          width: 130,
          render: props => {
            return <span>{props.row.isAllowDeleted + '' === '10041001' ? '是' : '否'}</span>;
          }
        },

        {
          title: '工时费',
          dataIndex: 'labourAmount',
          precision: 2

        },
        {
          title: '备件费',
          dataIndex: 'partAmount',
          precision: 2
        },
        {
          title: '附加项目费',
          dataIndex: 'addItemAmount',
          precision: 2
        },
        {
          title: '总金额',
          dataIndex: 'totalAmount',
          precision: 2,

        },

        {
          title: '发布人',
          dataIndex: 'releaseBy'
          // editable: false,
          // editType: 'select',
          // width: 120,
          // editItems: []
        },
        {
          title: '发布时间',
          dataIndex: 'releaseTime',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          width: 140,

          // editable: false,
          // editType: 'select',
          // editItems: []
        },
      ];
    },

    async invalid(row) {
      const res = await changeStatus(row);
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '作废成功' });
        this.fetchParams = { ...this.fetchParams };
      }
    },

    emitFun(val, type) {
      this.handleType = type;
      this.dialogTitle = `基本信息`;
      this.formData = val;
      this.estimate = true;
    },

    addEstimate() {
      // 新建
      this.handleType = 'add';
      this.showHandler();
    },
    showHandler() {
      // 显示
      this.dialogTitle = `基本信息`;
      this.estimate = true;
    },
    // selectData(val) {
    //   this.tableData = val;
    //   if (val.length == 0) {
    //     this.selectFlag = false;
    //   } else {
    //     this.selectFlag = true;
    //   }
    // },
    //选中
    selectData(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    closeEstimate(val, type) {
      // 关闭
      this.estimate = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 设置字段禁用状态
    setFieldHidden() {
      if (getAppId() == 'beijing') {
        this.topFilterList.find(item => item.fieldName == 'CHARGE_PARTITION_CODE').hidden = true;
        this.columns.find(item => item.dataIndex == 'CHARGE_PARTITION_CODE').hidden = true;
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
